// pages/setting/setting.js
Page({
  data: {
    phoneNumber: '',
    studentInfo: {}
  },

  onLoad(options) {
    this.loadStudentInfo();
  },

  onShow() {
    // 页面显示时重新加载学生信息，确保数据最新
    this.loadStudentInfo();
  },

  // 从本地存储加载学生信息
  loadStudentInfo() {
    const studentInfo = wx.getStorageSync('studentInfo');
    if (studentInfo) {
      // 格式化手机号显示（中间用*号隐藏）
      const formattedPhone = this.formatPhoneNumber(studentInfo.phone);
      
      this.setData({
        studentInfo: studentInfo,
        phoneNumber: formattedPhone || '未设置'
      });
    } else {
      // 如果没有登录信息，跳转到登录页
      wx.redirectTo({
        url: '/pages/logs/logs'
      });
    }
  },

  // 格式化手机号（保护隐私）
  formatPhoneNumber(phone) {
    if (!phone) return '';
    if (phone.length !== 11) return phone;
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  },

  // 手机号点击事件 - 显示完整手机号
  onPhoneClick() {
    const fullPhone = this.data.studentInfo.phone;
    if (!fullPhone) {
      wx.showModal({
        title: '提示',
        content: '您尚未设置手机号',
        showCancel: false,
        confirmText: '知道了'
      });
      return;
    }

    wx.showModal({
      title: '手机号',
      content: fullPhone,
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 修改手机号点击事件
  onChangePhoneClick() {
    const currentPhone = this.data.studentInfo.phone || '';
    
    wx.showModal({
      title: '修改手机号',
      editable: true,
      placeholderText: currentPhone || '请输入11位手机号',
      success: (res) => {
        if (res.confirm) {
          const newPhone = res.content.trim();
          if (newPhone) {
            this.updatePhoneNumber(newPhone);
          } else {
            wx.showToast({
              title: '手机号不能为空',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 更新手机号
  updatePhoneNumber(newPhone) {
    // 手机号格式验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(newPhone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '更新中...',
    });

    // 更新本地存储的学生信息
    const updatedStudentInfo = {
      ...this.data.studentInfo,
      phone: newPhone
    };

    // 保存到本地存储
    wx.setStorageSync('studentInfo', updatedStudentInfo);
    
    // 更新页面显示（格式化显示）
    const formattedPhone = this.formatPhoneNumber(newPhone);
    this.setData({
      phoneNumber: formattedPhone,
      studentInfo: updatedStudentInfo
    });

    wx.hideLoading();
    wx.showToast({
      title: '手机号已更新',
      icon: 'success',
      duration: 2000
    });

    // 可选：同步到服务器
    // this.syncPhoneToServer(newPhone);
  },

  // 同步手机号到服务器（可选）
  async syncPhoneToServer(newPhone) {
    try {
      // 注意：这里需要根据你的实际接口调整
      // 如果 updateStudent 导入有问题，可以在这里直接定义
      const updateStudent = (studentData) => {
        return new Promise((resolve, reject) => {
          wx.request({
            url: 'http://localhost:48080/app-api/mp/open/student/update',
            method: 'PUT',
            data: studentData,
            success: (res) => {
              resolve(res.data);
            },
            fail: (error) => {
              reject(error);
            }
          });
        });
      };
      
      const submitData = {
        id: this.data.studentInfo.id,
        studentNo: this.data.studentInfo.studentNo,
        studentName: this.data.studentInfo.studentName,
        gender: this.data.studentInfo.gender,
        age: this.data.studentInfo.age || 0,
        classId: this.data.studentInfo.classId || 0,
        majorDictId: this.data.studentInfo.majorDictId || 0,
        gradeDictId: this.data.studentInfo.gradeDictId || 0,
        education: this.data.studentInfo.education || '',
        phone: newPhone, // 更新手机号
        enrollTime: this.data.studentInfo.enrollTime || '',
        status: this.data.studentInfo.status || 0,
        medicalHistory: this.data.studentInfo.medicalHistory || '无',
        psychologicalHistory: this.data.studentInfo.psychologicalHistory || '无',
        familySituation: this.data.studentInfo.familySituation || '正常',
        psychologicalTestResult: this.data.studentInfo.psychologicalTestResult || '正常'
      };

      const result = await updateStudent(submitData);
      if (result.code === 0) {
        console.log('手机号同步到服务器成功');
      } else {
        console.error('手机号同步失败:', result.msg);
        // 可以给用户提示，但不影响本地更新
        wx.showToast({
          title: '更新成功（服务器同步失败）',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('同步手机号到服务器失败:', error);
      // 网络错误不影响本地更新
      wx.showToast({
        title: '更新成功（网络异常）',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 密码设置点击事件
  onPasswordClick() {
    wx.navigateTo({
      url: '/pages/password/password'
    });
  },

  // 退出登录
  handleLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          this.performLogout();
        }
      }
    });
  },

  // 执行退出登录
  performLogout() {
    wx.showLoading({
      title: '退出中...',
    });

    setTimeout(() => {
      wx.hideLoading();
      
      // 清除所有本地存储的登录信息
      try {
        wx.removeStorageSync('studentInfo');
        wx.removeStorageSync('isLoggedIn');
        wx.removeStorageSync('token');
        wx.removeStorageSync('userInfo');
        wx.removeStorageSync('refreshToken');
      } catch (e) {
        console.error('清除存储失败:', e);
      }

      wx.showToast({
        title: '退出成功',
        icon: 'success',
        duration: 1500
      });

      // 跳转到登录页面
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/index/index'
        });
      }, 1500);
    }, 1000);
  }
});